package com.bah.tract.client.ui;

import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.SwingUtilities;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bah.tract.client.ErrorHandler;
import com.bah.tract.service.TractServiceException_Exception;
import com.bah.tract.service.WorkService;
import com.google.inject.Inject;
import com.google.inject.name.Named;

public class IconMouseListener extends MouseAdapter {

	private final class ClickTimerTask extends TimerTask {
		@Override
		public void run() {
			if (!doubleClick) {
				LOG.debug("Single click.");
				try {
					SwingUtilities.invokeAndWait(new Runnable() {

						@Override
						public void run() {
							try {
								mWorkService.logWork(null);
							} catch (final TractServiceException_Exception e) {
								ErrorHandler.handleError(e);
							}
							mTimer.toggle();
						}
					});
				} catch (final InterruptedException e) {
					ErrorHandler.handleError(e);
				} catch (final InvocationTargetException e) {
					ErrorHandler.handleError(e);
				}
			}
		}
	}

	private final Integer doubleClickTime = (Integer) Toolkit
			.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");

	private boolean doubleClick;

	private final Component taskSelector;
	private final com.bah.tract.client.Timer mTimer;

	private final WorkService mWorkService;

	private static final Logger LOG = LoggerFactory
			.getLogger(IconMouseListener.class);

	@Inject
	public IconMouseListener(final com.bah.tract.client.Timer timer,
			@Named("taskSelector") final java.awt.Component taskSelector,
			final WorkService workService) {
		mTimer = timer;
		mWorkService = workService;
		this.taskSelector = taskSelector;
	}

	@Override
	public final void mouseClicked(final MouseEvent e) {
		final Timer timer = new Timer();

		if (MouseEvent.BUTTON1 == e.getButton()) {
			doubleClick = false;
			if ((e.getClickCount() == 2) && !e.isConsumed()) {
				doubleClick = true;
				LOG.debug("Double click.");
				e.consume();
				taskSelector.setVisible(true);
			} else {
				timer.schedule(new ClickTimerTask(), doubleClickTime);

			}
		}
	}
}